package com.ztewatch.wearcontacts;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.app.LoaderManager.LoaderCallbacks;
import android.content.ContentUris;
import android.content.Context;
import android.content.CursorLoader;
import android.content.Intent;
import android.content.Loader;
import android.database.Cursor;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.provider.ContactsContract.Contacts;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.CursorAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.ztewatch.wearcontacts.utils.ContactQuery;

public class WearContactsListActivity extends Activity implements
		OnItemClickListener {
	private ListView mListview;
	private MyCursorAdapter mMyCursorAdapter;
	private static final String SORT_KEY_ORDER = Contacts.PINNED
			+ " COLLATE NOCASE ASC";

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_wear_contacts_list);

		initview();
	}

	private void initview() {
		mMyCursorAdapter = new MyCursorAdapter(this, null);
		mListview = (ListView) findViewById(R.id.contactlistview);
		mListview.setAdapter(mMyCursorAdapter);
		mListview.setOnItemClickListener(this);
		// mListview.setOnItemLongClickListener(this);
	}

	class MyCursorAdapter extends CursorAdapter {
		Context mContext = null;
		LayoutInflater mInflater;

		public MyCursorAdapter(Context context, Cursor c) {
			super(context, c);
			mContext = context;
			mInflater = (LayoutInflater) context
					.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		}

		@Override
		public View newView(Context context, Cursor cursor, ViewGroup parent) {
			return mInflater.inflate(R.layout.contact_list_item, parent, false);
		}

		@Override
		public void bindView(View view, Context context, Cursor cursor) {
			final TextView name_tv = (TextView) view
					.findViewById(R.id.name_textview);
			final ImageView photo = (ImageView) view
					.findViewById(R.id.contact_img);
			if (cursor != null) {
				int name_index = cursor
						.getColumnIndex(Contacts.DISPLAY_NAME_PRIMARY);
				if (name_index != -1) {
					String name = cursor.getString(name_index);
					name_tv.setText(name);
				}
				bindPhoto(photo, cursor);
			}
		}

		private void bindPhoto(ImageView photo, Cursor cursor) {
			long photoId = 0;
			int index = cursor.getColumnIndex(Contacts.PHOTO_ID);
			if (index != -1) {
				if (!cursor.isNull(index)) {
					photoId = cursor.getLong(index);
				}
			}
			if (photoId != 0) {
				int id_index = cursor.getColumnIndex(Contacts._ID);
				if (id_index != -1) {
					Long contactID = cursor.getLong(id_index);
					Uri uri = ContentUris.withAppendedId(
							ContactsContract.Contacts.CONTENT_URI, contactID);
					InputStream input = ContactsContract.Contacts
							.openContactPhotoInputStream(
									mContext.getContentResolver(), uri);
					photo.setImageBitmap(BitmapFactory.decodeStream(input));
				}
			} else {
				photo.setImageResource(R.drawable.ic_address_portrait);
			}
		}

		public List<String> getLookUpKeys() {
			List<String> list = new ArrayList<String>();
			for (int index = 0; index < getCount(); index++) {
				Cursor cursor = (Cursor) getItem(index);
				if (cursor == null) {
					continue;
				}
				int lookup_key_index = cursor
						.getColumnIndex(Contacts.LOOKUP_KEY);
				if (lookup_key_index != -1) {
					String lookupKey = cursor.getString(lookup_key_index);
					list.add(lookupKey);
				}
			}
			return list;
		}
	}

	private final LoaderCallbacks<Cursor> loaderCallbacks = new LoaderCallbacks<Cursor>() {

		@Override
		public void onLoaderReset(Loader<Cursor> arg0) {

		}

		@Override
		public void onLoadFinished(Loader<Cursor> arg0, Cursor arg1) {
			mMyCursorAdapter.swapCursor(arg1);
		}

		@Override
		public Loader<Cursor> onCreateLoader(int id, Bundle args) {
			Uri uri = Contacts.CONTENT_URI;
			CursorLoader cursorLoader = new CursorLoader(
					WearContactsListActivity.this);
			final Uri.Builder builder = uri.buildUpon();
			// builder.appendQueryParameter(ContactsContract.DIRECTORY_PARAM_KEY,
			// String.valueOf(Directory.DEFAULT));
			// builder.appendQueryParameter(Contacts.EXTRA_ADDRESS_BOOK_INDEX,
			// "true");
			uri = builder.build();
			cursorLoader.setUri(uri);
			cursorLoader.setProjection(ContactQuery.CONTACT_PROJECTION);
			cursorLoader.setSortOrder(SORT_KEY_ORDER);
			return cursorLoader;
		}
	};

	@Override
	protected void onStart() {
		super.onStart();
		getLoaderManager().initLoader(0, null, loaderCallbacks);
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		getLoaderManager().destroyLoader(0);
	}

	@Override
	public void onItemClick(AdapterView<?> parent, View view, int position,
			long id) {
		Cursor cursor = (Cursor) mMyCursorAdapter.getItem(position);
		if (cursor != null) {
			Uri contactUri = getContactUri(cursor);
			Intent intent = new Intent(WearContactsListActivity.this,
					WearContactDisplayActivity.class);
			intent.setData(contactUri);
			startActivity(intent);
		}
	}

	public Uri getContactUri(Cursor cursor) {
		Uri uri = null;
		int id_index = cursor.getColumnIndex(Contacts._ID);
		int lookup_key_index = cursor.getColumnIndex(Contacts.LOOKUP_KEY);
		if (id_index != -1 && lookup_key_index != -1) {
			long contactId = cursor.getLong(id_index);
			String lookupKey = cursor.getString(lookup_key_index);
			uri = Contacts.getLookupUri(contactId, lookupKey);
		}
		return uri;
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		super.onCreateOptionsMenu(menu);

		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.contact_list_menu, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case R.id.contact_menu_share:
			ShareProgressThread shareProgressThread = new ShareProgressThread();
			shareProgressThread.start();
			break;
		}
		return super.onOptionsItemSelected(item);
	}

	private class ShareProgressThread extends Thread {

		StringBuilder uriListBuilder = new StringBuilder();
		public boolean mCanceled = false;

		public void run() {
			int k = 0;
			String lookupKey = null;
			List<String> list = mMyCursorAdapter.getLookUpKeys();

			while (!mCanceled && k < list.size()) {
				lookupKey = list.get(k);
				lookupKey = lookupKey.replaceAll(":", "__zz__");

				if (k != 0) {
					uriListBuilder.append(':');
				}
				uriListBuilder.append(lookupKey);
				k++;
			}
			try {
				Uri uri = Uri.withAppendedPath(
						Contacts.CONTENT_MULTI_VCARD_URI,
						Uri.encode(uriListBuilder.toString()));
				final Intent intent = new Intent(Intent.ACTION_SEND);
				intent.setType(Contacts.CONTENT_VCARD_TYPE);
				intent.putExtra(Intent.EXTRA_STREAM, uri);
				final Intent chooseIntent = Intent.createChooser(intent, "");
				startActivity(chooseIntent);
			} catch (Exception e) {
				e.printStackTrace();
			} finally {
				uriListBuilder = null;
			}
		}
	}
}
